<?php

namespace app\api\controller;

use think\Request;
use think\Db;
use app\common\adapter\AuthAdapter;
use app\common\controller\Common;


class Base extends Common
{
    public $user_id = '';

    public function _initialize()
    {
        parent::_initialize();
        $header = Request::instance()->param();
        $authKey = $header['token'];
        $cache = cache('Auth_' . $authKey);
        // 校验sessionid和authKey
        if (empty($authKey) || empty($cache) || !$cache) {
            header('Content-Type:application/json; charset=utf-8');
            exit(json_encode(['code' => 104, 'error' => '登录已失效']));
        }

        // 检查账号有效性
        $userInfo = $cache['userInfo'];
        $GLOBALS['userInfo'] = $userInfo;
        $this->user_id = $map['id'] = $userInfo['id'];
        $map['status'] = 1;
        if (!$user_data = Db::name('admin_user')->where($map)->value('id')) {
            header('Content-Type:application/json; charset=utf-8');
            exit(json_encode(['code' => 101, 'error' => '账号已被删除或禁用']));
        }

        //更新缓存
        cache('Auth_' . $authKey, $cache, config('LOGIN_SESSION_VALID'));
        $authAdapter = new AuthAdapter($authKey);
        $request = Request::instance();
        $ruleName = $request->module() . '-' . $request->controller() . '-' . $request->action();
        //var_dump($ruleName);
        if (!$authAdapter->checkLogin($ruleName, $cache['userInfo']['id'])) {
            header('Content-Type:application/json; charset=utf-8');
            exit(json_encode(['code' => 103, 'error' => '没有权限']));
        }
        $request = Request::instance();
        $ruleName = $request->module() . '-' . $request->controller() . '-' . $request->action();

        //热词模型生成结束的钩子
        $arg = [
            'uid' => $this->user_id,
            'rule' => $ruleName,
            'comment' => $request->param(),
        ];
        //日志记录
        $logModel = new \app\common\Log(new \app\api\model\Log());
        $logModel->info('log', $arg);
    }
}
